package com.stylefeng.guns.modular.ipmng.service.impl;

import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.stylefeng.guns.modular.ipmng.dao.BdapWhiteipListMapper;
import com.stylefeng.guns.modular.ipmng.model.BdapWhiteipList;
import com.stylefeng.guns.modular.ipmng.service.IIpWhiteListService;

/**
 * IP白名单管理Dao
 *
 * @author xiongyao
 * @Date 2017-11-15 10:08:12
 */
@Service
public class IpWhiteListServiceImpl implements IIpWhiteListService {

	private static final Logger logger = LoggerFactory
			.getLogger(IpWhiteListServiceImpl.class);

	@Autowired
	private BdapWhiteipListMapper mapper;

	@Override
	public boolean isAllowed(String clientIp) {
		// TODO Auto-generated method stub
		List<BdapWhiteipList> list = mapper.selectWhiteIpList();
		String[] userRemoteIp = clientIp.split("[.]");
		if (userRemoteIp.length == 1) {
			return true;
		}
		if (list.isEmpty()) {
			logger.info("白名单为空");
			return true;
		} else {
			for (BdapWhiteipList whiteips : list) {
				List<String> ips = Arrays.asList(whiteips.getIp().split(","));
				for (String ip : ips) {
					String[] ipsplit = ip.split("[.]");
					for (int i = 0; i < 4; i++) {
						if (ipsplit[i].equals("*")) {
							ipsplit[i] = userRemoteIp[i];
						}
					}
					if (clientIp.equals(String.join(".", ipsplit))) {
						logger.info("在白名单中找到用户IP，可以使用本系统");
						return true;
					}
				}
			}
			logger.info("在白名单中没有找到用户IP，不可以使用本系统");
			return false;
		}
	}
}
